//
//  UIViewController+SSO.m
//  jiajia
//
//  Created by rujia chen on 16/5/1.
//  Copyright © 2016年 sunrisin. All rights reserved.
//

#import "UIViewController+SSO.h"

@implementation UIViewController (SSO)

- (NSURLSessionTask *)gainCaptchaWithMobile:(NSString *)mobile andPurpose:(JJCaptchaPurpose)purpose successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    NSDictionary *params = @{@"id":mobile,
                             @"purpose": @(purpose)};
    
    return [[JJHttpClient client] GET:CONCAT_URL(@"/sso/mobile/identifyingcode") params:params successBlock:successBlock failBlock:failBlock exceptionBlock:exceptionBlock];
}

- (NSURLSessionTask *)doRegisterWithID:(NSString *)uid andPassword:(NSString *)password andCaptcha:(NSString *)captcha successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    NSDictionary *params = @{@"id":uid,
                             @"password":password,
                             @"purpose":@(0),
                             @"identifyingcode": captcha};
    
    return [[JJHttpClient client] POST:CONCAT_URL(@"/sso/mobile/registration") params:params successBlock:successBlock failBlock:failBlock exceptionBlock:exceptionBlock];
}

- (NSURLSessionTask *)doLogInWithID:(NSString *)uid andPassword:(NSString *)password successBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    NSDictionary *params = @{@"id":uid,
                             @"password":password};
    
    return [[JJHttpClient client] POST:CONCAT_URL(@"/sso/mobile/login") params:params successBlock:^(NSURLSessionTask *task, NSDictionary *response) {
        
        //登陆环信
        [self loginEaseMobWithUserName:uid
                                andPwd:kEaseMobGlobalPwd
                      andOnFinishLogin:^{
                          if (successBlock) successBlock(task, response);
                          
                          //保存sessionid
                          NSString *sessionid = response[@"sessionid"];
                          [[JJHttpClient client] addValue:sessionid forHTTPHeaderField:@"x-sid"];
                          [[NSUserDefaults standardUserDefaults] setObject:sessionid forKey:UDKeyForSessionID];
                          [[NSUserDefaults standardUserDefaults] synchronize];
                          
                          //发送通知
                          [[NSNotificationCenter defaultCenter] postNotificationName:NCLoginStatusChangedNotification object:@(YES)];
                      }];
        
    } failBlock:failBlock exceptionBlock:exceptionBlock];
}

- (NSURLSessionTask *)doLogOutWithSuccessBlock:(SuccessBlock)successBlock failBlock:(FailBlock)failBlock exceptionBlock:(ExceptionBlock)exceptionBlock {
    return [[JJHttpClient client]DELETE:CONCAT_URL(@"/sso/logout") params:nil successBlock:^(NSURLSessionTask *task, NSDictionary *response) {
        if (successBlock) successBlock(task, response);
        
        //移除sessionid
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:UDKeyForSessionID];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:NCLoginStatusChangedNotification object:@(NO)];
        
        //登出环信
        [self logoutEaseMob];
    } failBlock:failBlock exceptionBlock:exceptionBlock];
}

#pragma mark - private

- (void)loginEaseMobWithUserName:(NSString*)userName andPwd:(NSString*)pwd andOnFinishLogin:(void(^)())finishLoginBlock {
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:userName password:pwd completion:^(NSDictionary *loginInfo, EMError *error) {
        if (error.errorCode == EMErrorNotFound) {
            [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:userName password:pwd withCompletion:^(NSString *username, NSString *password, EMError *error) {
                [self loginEaseMobWithUserName:userName andPwd:pwd andOnFinishLogin:finishLoginBlock];
            } onQueue:nil];
        }else {
            [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
            LogIM(@"[login finish]%@",userName);
            if (finishLoginBlock) {
                finishLoginBlock();
            }
        }
    } onQueue:nil];
}

- (void)logoutEaseMob {
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
        if (error) {
            [self logoutEaseMob];
        }else {
            LogIM(@"[logout finish]");
        }
    } onQueue:nil];
}

@end
